package cn.com.tiptop.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

/**
 * 获取资源工具
 * @author qing
 *
 */
public class MyResource {

	private static MyResource myResource = null;

	/**
	 * 得到jar配置文件路径
	 */
	public static String getJarPath() throws Exception {
		return new File(java.net.URLDecoder.decode(
				getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"))
						.getParentFile().getAbsolutePath()
				+ File.separatorChar;
	}

	/**
	 * 得到jar包同级的Properties文件
	 * 
	 * @param fileName
	 * @return
	 */
	public static Properties getJarProperties(String fileName) {
		try {
			Properties properties = new Properties();
			InputStream in = new BufferedInputStream(new FileInputStream(getJarPath() + fileName));
			properties.load(in);
			return properties;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 加载jar包内Properties文件
	 * 
	 * @param fileName
	 * @return
	 */
	public static Properties getSrcProperties(String fileName) {
		try {
			Properties properties = new Properties();
			InputStream in = getInstance().getClass().getClassLoader().getResourceAsStream(fileName);
			properties.load(in);
			return properties;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 得到某路径下的Properties文件
	 * 
	 * @param filePath
	 * @return
	 */
	public static Properties getProperties(String filePath) {
		try {
			Properties properties = new Properties();
			InputStream in = new BufferedInputStream(new FileInputStream(filePath));
			properties.load(in);
			return properties;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 单例
	 * @return
	 */
	private static MyResource getInstance() {
		if (myResource == null) {
			synchronized (MyResource.class) {
				if (myResource == null) {
					myResource = new MyResource();
				}
			}
		}
		return myResource;
	}
}
